package com.zhuangfei.timetable.operater;


import com.zhuangfei.timetable.ResourceTable;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.model.ScheduleConfig;
import com.zhuangfei.timetable.model.ScheduleSupport;
import com.zhuangfei.timetable.utils.AttrUtils;
import com.zhuangfei.timetable.utils.ScreenUtils;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 课表业务操作者，TimetableView中只涉及属性的设置，方法的具体实现在这里.
 * 常用的方法也就四个，如下
 *
 * @see SimpleOperater#changeWeek(int, boolean)
 * @see SimpleOperater#showView()
 * @see SimpleOperater#updateDateView()
 * @see SimpleOperater#updateSlideView()
 * <p>
 * Created by Liu ZhuangFei on 2018/9/1.
 */
public class SimpleOperater extends AbsOperater {
    private static final HiLogLabel LOG_LABEL = new HiLogLabel(3, 0, "SimpleOperater");
    protected TimetableView mView;
    protected Context context;

    /**
     * 保存点击的坐标
     */
    protected float x;
    protected float y;

    /**
     * 布局转换器
     */
    protected LayoutScatter inflater;
    /**
     * 侧边栏
     */
    protected DirectionalLayout weekPanel;
    /**
     * 每天的课程
     */
    protected List<Schedule>[] data = new ArrayList[7];
    /**
     * 每天的面板
     */
    protected DirectionalLayout[] panels = new DirectionalLayout[7];
    /**
     * 根布局
     */
    protected DirectionalLayout containerLayout;
    /**
     * 根布局、日期栏容器
     */
    protected DirectionalLayout dateLayout;
    /**
     * 旗标布局
     */
    protected DirectionalLayout flagLayout;

    protected ScheduleConfig scheduleConfig;
    /**
     * 初始月份长度
     */
    protected final static int MONTH_WIDTH = 80;

    @Override
    public void init(Context context, AttrSet attrs, TimetableView view) {
        this.context = context;
        mView = view;
        inflater = LayoutScatter.getInstance(context);
        inflater.parse(ResourceTable.Layout_timetable_layout, mView, true);

        containerLayout = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_id_container);
        dateLayout = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_id_datelayout);
        mView.monthWidthDp(MONTH_WIDTH);
        initAttr(attrs);
        scheduleConfig = new ScheduleConfig(context);

    }

    /**
     * 获取自定义属性
     *
     * @param attrs
     */
    protected void initAttr(AttrSet attrs) {
        if (attrs == null) {
            return;
        }
        int curWeek = AttrUtils.getInt(attrs, "cur_week", 1);

        String curTerm = AttrUtils.getString(attrs, "cur_term", null);


        int defMarTop = 5;
        int defMarLeft = 5;
        int defItemHeight = 150;
        int marTop = AttrUtils.getInt(attrs, "mar_top", defMarTop);

        int marLeft = AttrUtils.getInt(attrs, "mar_left", defMarLeft);

        int itemHeight = AttrUtils.getInt(attrs, "item_height", defItemHeight);

        int thisWeekCorner = AttrUtils.getInt(attrs, "thisweek_corner", 5);

        int nonWeekCorner = AttrUtils.getInt(attrs, "nonweek_corner", 5);

        int maxSlideItem = AttrUtils.getInt(attrs, "max_slide_item", 12);

        boolean isShowNotWeek = AttrUtils.getBoolean(attrs, "show_notcurweek", true);

        mView.curWeek(curWeek)
                .curTerm(curTerm)
                .marTop(marTop)
                .marLeft(marLeft)
                .itemHeight(itemHeight)
                .corner(thisWeekCorner, true)
                .corner(nonWeekCorner, false)
                .maxSlideItem(maxSlideItem)
                .isShowNotCurWeek(isShowNotWeek);
    }

    @Override
    public DirectionalLayout getDateLayout() {
        return dateLayout;
    }

    /**
     * 获取旗标布局,需要在showView方法执行后执行
     *
     * @return DirectionalLayout
     */
    @Override
    public DirectionalLayout getFlagLayout() {
        return flagLayout;
    }

    /**
     * 构建侧边栏
     *
     * @param slidelayout 侧边栏的容器
     */
    public void newSlideView(DirectionalLayout slidelayout) {
        if (slidelayout == null) {
            return;
        }
        /**
         * 更新UI的操作
         */
        context.getUITaskDispatcher().asyncDispatch(() -> {
            slidelayout.removeAllComponents();
        });

        ISchedule.OnSlideBuildListener listener = mView.onSlideBuildListener();
        listener.onInit(slidelayout, mView.slideAlpha());
        for (int i = 0; i < mView.maxSlideItem(); i++) {
            Component view = listener.getView(i, inflater, mView.itemHeight(), mView.marTop());
            context.getUITaskDispatcher().asyncDispatch(() -> {
                slidelayout.addComponent(view);
            });

        }
    }

    /**
     * newItemView
     *
     * @param originData 数据源
     * @param data       某一天的数据集合
     * @param subject    当前的课程数据
     * @param pre        上一个课程数据
     * @param i          构建的索引
     * @param curWeek    当前周
     * @return View
     */
    private Component newItemView(final List<Schedule> originData, final List<Schedule> data,
                                  final Schedule subject, Schedule pre, int i, int curWeek) {
        /**
         * 宽高
         */
        int width = DirectionalLayout.LayoutConfig.MATCH_PARENT;
        int height = mView.itemHeight() * subject.getStep() + mView.marTop() * (subject.getStep() - 1);

        /**
         * 边距
         */
        int left = mView.marLeft() / 2;
        int right = mView.marLeft() / 2;
        int top = (subject.getStart() - (pre.getStart() + pre.getStep()))
                * (mView.itemHeight() + mView.marTop()) + mView.marTop();

        if (i != 0 && top < 0) {
            return null;
        }

        /**
         * 设置Params
         */
        Component view = inflater.parse(ResourceTable.Layout_item_timetable, null, false);

        StackLayout.LayoutConfig lp = new StackLayout.LayoutConfig(width, height);
        if (i == 0) {
            top = (subject.getStart() - 1) * (mView.itemHeight() + mView.marTop()) + mView.marTop();
        }
        lp.setMargins(left, top, right, 0);
        int value = Color.TRANSPARENT.getValue();
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(new RgbColor(value));
        view.setBackground(shapeElement);
        view.setTag(subject);
        StackLayout layout = (StackLayout) view.findComponentById(ResourceTable.Id_id_course_item_framelayout);
        layout.setLayoutConfig(lp);

        boolean isThisWeek = ScheduleSupport.isThisWeek(subject, curWeek);

        ShapeElement textElement = new ShapeElement();
        textElement.setCornerRadius(5);
        textElement.setRgbColor(new RgbColor(140, 216, 97));
        Text textView = (Text) view.findComponentById(ResourceTable.Id_id_course_item_course);
        textView.setText(mView.onItemBuildListener().getItemText(subject, isThisWeek));
        textView.setBackground(textElement);

        ShapeElement countElement = new ShapeElement();
        countElement.setCornerRadius(50);
        countElement.setRgbColor(new RgbColor(216, 30, 6));
        Text countTextView = (Text) view.findComponentById(ResourceTable.Id_id_course_item_count);
        countTextView.setText("");
        countTextView.setVisibility(Component.HIDE);
        countTextView.setBackground(countElement);

        ShapeElement gd = new ShapeElement();
        if (isThisWeek) {
            textView.setTextColor(new Color(mView.itemTextColorWithThisWeek()));
            Map<String, RgbColor> colorMap = mView.colorPool().getColorMap();
            if ((!colorMap.isEmpty()) && colorMap.containsKey(subject.getName())) {
                gd.setRgbColor(new RgbColor(colorMap.get(subject.getName())));
            } else {
                gd.setRgbColor(new RgbColor(mView.colorPool().getColorAutoWithAlpha(subject.getColorRandom())));
            }
            gd.setAlpha(mView.itemAlpha());
            gd.setCornerRadius(mView.corner(true));

            List<Schedule> clist = ScheduleSupport.findSubjects(subject, originData);
            int count = 0;
            if (clist != null) {
                for (int k = 0; k < clist.size(); k++) {
                    Schedule p = clist.get(k);
                    if (p != null && ScheduleSupport.isThisWeek(p, curWeek)) {
                        count++;
                    }
                }
            }
            if (count > 1) {
                countTextView.setVisibility(Component.VISIBLE);
                countTextView.setText(count + "");
            }
        } else {
            textView.setTextColor(new Color(mView.itemTextColorWithNotThis()));
            Map<String, RgbColor> colorMap = mView.colorPool().getColorMap();
            if ((!colorMap.isEmpty()) && mView.colorPool().isIgnoreUserlessColor()
                    && colorMap.containsKey(subject.getName())) {
                gd.setRgbColor(new RgbColor(colorMap.get(subject.getName())));
            } else {
                gd.setRgbColor(new RgbColor(mView.colorPool().getUselessColorWithAlpha()));
            }
            gd.setAlpha(mView.itemAlpha());
            gd.setCornerRadius(mView.corner(false));
        }

        textView.setBackground(gd);
        mView.onItemBuildListener().onItemUpdate(layout, textView, countTextView, subject, gd);

        textView.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                List<Schedule> result = ScheduleSupport.findSubjects(subject, originData);
                mView.onItemClickListener().onItemClick(component, result);
            }
        });

        textView.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                mView.onItemLongClickListener().onLongClick(view, subject.getDay(), subject.getStart());
            }
        });
        return view;
    }

    /**
     * 将数据data添加到layout的布局上
     *
     * @param layout  容器
     * @param data    某一天的数据集合
     * @param curWeek 当前周
     */
    private void addToLayout(DirectionalLayout layout, final List<Schedule> data, int curWeek) {
        if (layout == null || data == null || data.size() < 1) {
            return;
        }
        context.getUITaskDispatcher().asyncDispatch(() -> {
            layout.removeAllComponents();
        });

        /**
         * 遍历
         */
        List<Schedule> filter = ScheduleSupport.fliterSchedule(data, curWeek, mView.isShowNotCurWeek());
        Schedule pre = null;
        if (filter.size() > 0) {
            pre = filter.get(0);
        }
        for (int i = 0; i < filter.size(); i++) {
            final Schedule subject = filter.get(i);
            Component view = newItemView(data, filter, subject, pre, i, curWeek);
            if (view != null) {
                context.getUITaskDispatcher().asyncDispatch(() -> {
                    layout.addComponent(view);
                });
                pre = subject;
            }
        }
    }


    /**
     * 点击panel时的事件响应
     *
     * @param view
     * @param y
     */
    protected void onPanelClicked(Component view, float y) {
        if (mView.isShowFlaglayout()) {
            flagLayout.setVisibility(Component.VISIBLE);
        } else {
            flagLayout.setVisibility(Component.HIDE);
        }

        /**
         * 周几，0：周一，6：周日
         */
        int day = 0;

        /**
         * 先找到点击的是周几的panel
         */
        for (int i = 0; i < panels.length; i++) {
            if (view == panels[i]) {
                day = i;
                break;
            }
        }

        if (day == -1) {
            return;
        }

        /**
         * 判断点击的是第几节课，1：第1节
         */
        final int start;
        start = (int) Math.ceil(y / (mView.itemHeight() + mView.marTop()));
        if (!checkPosition(day, start)) {
            mView.onSpaceItemClickListener().onSpaceItemClick(day, start);
        }
        final int finalDay = day;
        flagLayout.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                mView.onFlaglayoutClickListener().onFlaglayoutClick(finalDay, start);
            }
        });

    }

    /**
     * 判断位置是否有课
     *
     * @param day
     * @param start
     * @return true：有课，false：无课
     */
    protected boolean checkPosition(int day, int start) {
        List<Schedule> list;
        if (mView.isShowNotCurWeek()) {
            list = ScheduleSupport.getAllSubjectsWithDay(mView.dataSource(), day);
        } else {
            list = ScheduleSupport.getHaveSubjectsWithDay(mView.dataSource(), mView.curWeek(), day);
        }
        boolean isHave = false;
        for (Schedule item : list) {
            if (start == item.getStart() || (start >= item.getStart() && start <= (
                    item.getStart() + item.getStep() - 1))) {
                isHave = true;
            }
        }
        return isHave;
    }


    /**
     * 初始化panel并为panel设置事件监听
     */
    protected void initPanel() {
        for (int i = 0; i < panels.length; i++) {
            panels[i] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_1 + i);
            data[i] = new ArrayList<>();

            /**
             * 点击空白格子时才会触发这个事件
             */
            panels[i].setTouchEventListener(new Component.TouchEventListener() {
                @Override
                public boolean onTouchEvent(Component arg0, TouchEvent arg1) {


                    MmiPoint point = arg1.getPointerPosition(arg1.getIndex());
                    switch (arg1.getAction()) {

                        case TouchEvent.PRIMARY_POINT_DOWN:
                            x = point.getX();
                            y = point.getY();

                            break;
                        case TouchEvent.PRIMARY_POINT_UP:
                            float x2 = point.getX();
                            float y2 = point.getY();
                            if (x2 == x && y2 == y) {
                                onPanelClicked(arg0, point.getY());
                            }

                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
        }
    }

    /**
     * 实现ScrollView的替换,只有在初始化时替换一次
     */
    public void replaceScrollView() {
        if (mView.findComponentById(ResourceTable.Id_id_scrollview) == null) {
            Component view = mView.onScrollViewBuildListener().getScrollView(inflater);
            containerLayout.addComponent(view);
            weekPanel = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_0);
            flagLayout = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_id_flaglayout);
            initPanel();
        }
    }

    /**
     * 设置旗标布局的配置
     */
    public void applyFlagLayoutConf() {
        mView.hideFlaglayout();
        DirectionalLayout.LayoutConfig lp = new DirectionalLayout.LayoutConfig(
                mView.monthWidth(), DirectionalLayout.LayoutConfig.MATCH_PARENT);
        weekPanel.setLayoutConfig(lp);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(new RgbColor(mView.flagBgcolor()));
        flagLayout.setBackground(shapeElement);
        float perWidth = getPerWidth();
        mView.onSpaceItemClickListener().onInit(flagLayout, mView.monthWidth(),
                Math.round(perWidth), mView.itemHeight(), mView.marTop(),
                Math.round(mView.marLeft() / 2.0f));
    }

    /**
     * 开始装填数据
     */
    public void startTodo() {
        /**
         * 清空、拆分数据
         */
        for (int i = 0; i < 7; i++) {
            data[i].clear();
        }
        List<Schedule> source = mView.dataSource();
        for (int i = 0; i < source.size(); i++) {
            Schedule bean = source.get(i);
            if (bean.getDay() != -1) {
                data[bean.getDay() - 1].add(bean);
            }
        }

        /**
         * 排序、填充课程
         */
        ScheduleSupport.sortList(data);
        for (int i = 0; i < panels.length; i++) {
            int finalI = i;
            panels[finalI].removeAllComponents();
            addToLayout(panels[finalI], data[finalI], mView.curWeek());
        }
    }

    /**
     * 设置宽度
     */
    public void applyWidthConfig() {
        setWeekendsVisiable(mView.isShowWeekends());
    }

    /**
     * 绘制课程表
     */
    @Override
    public void showView() {
        if (mView == null || mView.dataSource() == null) {
            return;
        }
        checkConfig();
        replaceScrollView();
        debug("showView: " + flagLayout);
        applyFlagLayoutConf();
        applyWidthConfig();

        /**
         * 更新日期
         */
        updateDateView();
        updateSlideView();
        startTodo();
    }

    /**
     * 本地配置的加载
     */
    private void checkConfig() {
        if (mView == null || mView.onConfigHandleListener() == null) {
            return;
        }
        if (mView.onConfigHandleListener() != scheduleConfig.getOnConfigHandleListener()) {
            scheduleConfig.setOnConfigHandleListener(mView.onConfigHandleListener());
        }
        scheduleConfig.setConfigName(mView.configName());
        scheduleConfig.use(mView);
    }

    /**
     * 切换周次
     *
     * @param week
     * @param isCurWeek 是否强制设置为当前周
     */
    @Override
    public void changeWeek(int week, boolean isCurWeek) {
        for (int i = 0; i < panels.length; i++) {
            addToLayout(panels[i], data[i], week);
        }
        if (isCurWeek) {
            mView.curWeek(week);
        } else {
            mView.onWeekChangedListener().onWeekChanged(week);
        }
    }

    /**
     * getPerWidth
     *
     * @return 宽度
     */
    protected float getPerWidth() {
        double perWidth = 0;
        if (mView.isShowWeekends()) {
            perWidth = ((double) ScreenUtils.getDisplayWidth(context) - (double) mView.monthWidth()) / 7;
        } else {
            perWidth = ((double) ScreenUtils.getDisplayWidth(context) - (double) mView.monthWidth()) / 5;
        }
        return (float) perWidth;
    }

    /**
     * 更新日期栏
     */
    public void updateDateView() {
        context.getUITaskDispatcher().asyncDispatch(() -> {
            dateLayout.removeAllComponents();
        });
        float perWidth = getPerWidth();
        int height = 150;
        /**
         * 日期栏
         */
        ISchedule.OnDateBuildListener listener = mView.onDateBuildListener();
        listener.onInit(dateLayout, mView.dateAlpha());
        Component[] views = mView.onDateBuildListener().getDateViews(inflater, mView.monthWidth(), perWidth, height);
        for (Component v : views) {
            if (v != null) {
                context.getUITaskDispatcher().asyncDispatch(() -> {
                    dateLayout.addComponent(v);
                });
            }
        }
        mView.onDateBuildListener().onUpdateDate(mView.curWeek(), mView.curWeek());
        mView.onDateBuildListener().onHighLight();
    }

    /**
     * 侧边栏更新
     */
    @Override
    public void updateSlideView() {
        newSlideView(weekPanel);
    }

    /**
     * 设置周末的可见性
     *
     * @param isShow
     */
    public void setWeekendsVisiable(boolean isShow) {
        if (isShow) {
            if (panels != null && panels.length > 6) {
                panels[5].setVisibility(Component.VISIBLE);
                panels[6].setVisibility(Component.VISIBLE);
            }
        } else {
            if (panels != null && panels.length > 6) {
                panels[5].setVisibility(Component.HIDE);
                panels[6].setVisibility(Component.HIDE);
            }
        }
    }

    /**
     * 日志显示
     *
     * @param message 日志信息
     */
    private void debug(String message) {
        HiLog.debug(LOG_LABEL, message);
    }
}
